import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import cookie from 'js-cookie'

// 创建axios实例
const service = axios.create({
  baseURL: "http://localhost:20000", // api 的 base_url
  timeout: 15000 // 请求超时时间
})

// http request 拦截器
service.interceptors.request.use(
  config => {
    //debugger
    if (cookie.get('edu_token')) {
      config.headers['token'] = cookie.get('edu_token');
    }
    return config
  },
  err => {
    return Promise.reject(err);
  })

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.code !== 20000) {
      if (res.code === 25000) {
        //订单支付中
        Message({
          message: res.message,
          type: 'warning',
          duration: 5 * 1000
        })
        return response.data
      } else {
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject('error')
      }

    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
